package com.college.collegeinfomanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.college.collegeinfomanage.dto.UserDTO;
import com.college.collegeinfomanage.entity.User;
import com.college.collegeinfomanage.mapper.UserMapper;
import com.college.collegeinfomanage.service.UserService;
import com.college.collegeinfomanage.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    public  String SING;

    @Override
    public void register( User user) {
        userMapper.insert(user);
    }

    @Override
    public UserVO login(User user) {
        log.info("签名：{}",SING);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        if(user.getUsername()!=null && !"".equals(user.getUsername())){
            queryWrapper.eq( User::getUsername,user.getUsername());
        }
        if(user.getPassword()!=null && !"".equals(user.getPassword())){
            queryWrapper.eq(User::getPassword,user.getPassword());
        }

        User selecUser = userMapper.selectOne(queryWrapper);
        UserVO vo = new UserVO();
        BeanUtil.copyProperties(selecUser, vo);


        //生成taken
        Map map =new HashMap();
        map.put("id",selecUser.getId());

        String token=  JWTUtil.createToken(map,SING.getBytes());

        vo.setToken(token);
        vo.setRole(selecUser.getRole());

        return  vo;
    }

    @Override
    public IPage<User> getPage(UserDTO userDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (userDTO.getUsername() != null && !"".equals(userDTO.getUsername())) {
            queryWrapper.like(User::getUsername, userDTO.getUsername());
        }
        if (userDTO.getRole() != null && !"".equals(userDTO.getRole())) {
            queryWrapper.eq(User::getRole, userDTO.getRole());
        }
        IPage<User> page = new Page<>(userDTO.getPage(), userDTO.getSize());
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
        return userIPage;
    }
}
